package com.freewater.springboot.demo.ioc.genericdi;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.ResolvableType;

import java.util.List;

public class Main {
    public static void main(String[] args) {
        final AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
        applicationContext.registerShutdownHook();

        AnimalBusiness animalBusiness = applicationContext.getBean(AnimalBusiness.class);
        animalBusiness.doSomeBusiness();

        CatBusiness catBusiness = applicationContext.getBean(CatBusiness.class);
        catBusiness.doSomeBusiness();

        DogBusiness dogBusiness = applicationContext.getBean(DogBusiness.class);
        dogBusiness.doSomeBusiness();

        ObjectProvider<Object> beanProvider = applicationContext.getBeanProvider(ResolvableType.forClassWithGenerics(List.class, Animal.class));
        List<Animal> list = (List<Animal>) beanProvider.getObject();
        System.out.println(list.size() + " animals");

        beanProvider = applicationContext.getBeanProvider(ResolvableType.forClassWithGenerics(List.class, AnimalBusiness.class));
        List<AnimalBusiness> businessList = (List<AnimalBusiness>) beanProvider.getObject();
        System.out.println(businessList.size() + " animalBusinesses");

        // 如果使用这个方法getBeanProvider(Class<T> requiredType)，则会获取到所有弱类型为List的Bean（这里为名为“animals”和“animalBusinesses”的两个Bean）
        ObjectProvider<List> listProvider = applicationContext.getBeanProvider(List.class);
        listProvider.forEach(System.out::println);
    }
}
